package com.therandoms.rtgdroid.background;

import java.io.File;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;

/**
 * 
 * @author logan
 *
 * @param <T>
 */
public class BitmapGenerationAsyncTask<T> extends AsyncTask<T, Integer, Uri> {

	/**
	 * The output directory to use for music.
	 */
	public static final String GENERATED_IMAGES_OUTPUT_DIRECTORY = "RandomTextGen"
			+ File.separator + "OutputImages";

	/**
	 * The number of bytes per "cluster" of pixels. This must be divisible by 4.
	 */
	private static final int NUM_BYTES_PER_CLUSTER = 16;

	@Override
	protected Uri doInBackground(T... params) {
		// create the required directories
		File extStorageDir = Environment.getExternalStorageDirectory();
		File outDir = new File(extStorageDir.getAbsolutePath() + File.separator
				+ GENERATED_IMAGES_OUTPUT_DIRECTORY);
		if (!outDir.mkdirs() && !outDir.isDirectory()) {
			return null;
		}

		// get the name of the file
		SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss",
				Locale.getDefault());
		String mDate = fmt.format(new Date());
		File mFile = new File(outDir.getAbsolutePath() + File.separator + mDate
				+ ".png");

		// get the bytes of the object
		byte srcBytes[] = params[0].toString().getBytes();

		// create data (including padding and clusters
		byte imgBytes[] = new byte[(srcBytes.length + (srcBytes.length % 4))
				* NUM_BYTES_PER_CLUSTER];
		for (int i = 0; i < srcBytes.length; i++) {
			for (int j = 0; j < NUM_BYTES_PER_CLUSTER; j++) {
				imgBytes[(i * NUM_BYTES_PER_CLUSTER) + j] = srcBytes[i];
			}
		}

		// get data
		IntBuffer colorBuf = ByteBuffer.wrap(imgBytes).asIntBuffer();
		colorBuf.rewind();
		int imgColors[] = new int[colorBuf.capacity()];
		colorBuf.get(imgColors);

		// compute dimensions
		int length = (int) Math.sqrt(imgColors.length);
		int width = length;

		// make bitmap
		try {
			Bitmap btmp = Bitmap.createBitmap(imgColors, width, length,
					Config.ARGB_8888);
			FileOutputStream fos = new FileOutputStream(mFile);
			btmp.compress(CompressFormat.PNG, 0, fos);
			fos.close();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

		// get the URI for an android action_send intent.
		return Uri.fromFile(mFile);
	}

}
